﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Net;
using FBEntities;
using System.IO;

namespace XDAFacebook
{
    public partial class LoginWeb : Form
    {
        private string exchangeUrl;
        private string accessCode;
        private string successUrl;
        public string token_text;
        public string token_permissions;
        public bool updated;

        public LoginWeb(string authUrl, string exchUrl, string sucUrl)
        {
            InitializeComponent();

            this.exchangeUrl = exchUrl;
            this.successUrl = sucUrl;

            if (this.wbLogin.IsOffline)
            {
                MessageBox.Show("Offline", "", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1);
            }
            else
            {
                this.wbLogin.Navigate(new Uri(authUrl));
            }
        }

        private void wbLogin_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            if (wbLogin.Url != null)
            {
                //Do nothing until we get successful login
                if (wbLogin.Url.AbsolutePath == this.successUrl)
                {
                    accessCode = wbLogin.Url.Query;
                    accessCode = accessCode.Remove(0, 6);

                    exchangeUrl += accessCode;

                    WebRequest myWebRequest = WebRequest.Create(exchangeUrl);
                    try
                    {
                        using (WebResponse myWebResponse = myWebRequest.GetResponse())
                        {
                            string responseData;
                            using (var resp = myWebResponse.GetResponseStream())
                            using (StreamReader streamReader = new StreamReader(resp))
                            {
                                responseData = streamReader.ReadToEnd();
                            }

                            token_text = responseData;
                            updated = true;
                        }
                    }
                    catch
                    {
                        updated = false;
                    }
                    // causing exception for some reason
                    //wbLogin.Dispose();
                    Close();
                }
            }

        }        
    }
}